package org.czf.zk;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

@Slf4j
public class ZooKeeperWatcherExample implements Watcher {

    // ZooKeeper 服务器地址
    private static final String ZOOKEEPER_ADDRESS = "47.115.227.96:2181";
    // 会话超时时间
    private static final int SESSION_TIMEOUT = 300000;
    // 节点路径
    private static final String NODE_PATH = "/example";

    // ZooKeeper 客户端
    private ZooKeeper zooKeeper;

    // 构造方法，在初始化时连接 ZooKeeper 服务器
    public ZooKeeperWatcherExample() {
        try {
            // 连接 ZooKeeper 服务器
            this.zooKeeper = new ZooKeeper(ZOOKEEPER_ADDRESS, SESSION_TIMEOUT, this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Watcher 接口的回调方法，处理节点状态变化事件
    @Override
    public void process(WatchedEvent event) {
        log.info("event = {}", JSON.toJSONString(event));
        // 节点状态变化事件
        if (event.getType() == Event.EventType.NodeDataChanged ||
                event.getType() == Event.EventType.NodeCreated ||
                event.getType() == Event.EventType.NodeDeleted) {
            // 重新获取节点数据，并注册监听器
            getNodeData();
        }
    }

    // 获取节点数据，并注册监听器
    private void getNodeData() {
        try {
            // 获取节点数据和状态信息
            Stat stat = new Stat();
            byte[] data = zooKeeper.getData(NODE_PATH, this, stat);
            String nodeData = new String(data);
            log.info("Node data: {}", nodeData);
            System.out.println("Node data: " + nodeData);

            // 注册监听器
            zooKeeper.exists(NODE_PATH, this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 设置节点数据
    public void setNodeData(String data) {
        try {
            // 检查节点是否存在
            Stat stat = zooKeeper.exists(NODE_PATH, false);
            if (stat != null) {
                // 设置节点数据
                zooKeeper.setData(NODE_PATH, data.getBytes(), stat.getVersion());
            } else {
                System.out.println("Node doesn't exist");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 主方法，用于演示
    public static void main(String[] args) throws InterruptedException {
        // 创建示例对象
        ZooKeeperWatcherExample example = new ZooKeeperWatcherExample();

        // 创建示例节点
        try {
            log.info("创建");
            example.zooKeeper.create(NODE_PATH, "Initial data".getBytes(),
                    ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 设置节点数据
        log.info("更新");
        example.setNodeData("Updated data");

        // 等待一段时间，观察节点状态变化
        log.info("睡眠");
        Thread.sleep(1000);
        log.info("睡眠end");

        // 关闭 ZooKeeper 连接
        try {
            example.zooKeeper.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

